package com.github.live.plugins.base;

import com.alibaba.fastjson.JSONReader;
import com.github.live.util.LogFactory;
import com.github.livebase.bean.IjkCodec;
import com.github.livebase.plugins.PluginContext;
import com.github.livebase.util.LiveContext;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName IjkCodecRegister
 * @description:
 * @author: biao532
 * @create: 2023-12-30 11:06
 * @Version 1.0
 **/
public class IjkCodecRegister implements com.github.livebase.plugins.IjkCodecRegister {
    @Override
    public List<IjkCodec> register(LiveContext liveContext, PluginContext context) {
        // /storage/emulated/0/Android/data/com.github.live/files/ijkCodec.json
        File file = new File(liveContext.getExternalFilesDir(""), "ijkCodec.json");
        if (!file.exists()) {
            LogFactory.info(IjkCodecRegister.class, "路径 {} 不存在", file.getAbsolutePath());
            return null;
        }
        try(InputStream inputStream = new FileInputStream(file)) {
            List<IjkCodec> codecs = new ArrayList<>();
            JSONReader reader = new JSONReader(new InputStreamReader(inputStream));
            reader.startArray();
            while (reader.hasNext()) {
                codecs.add(reader.readObject(IjkCodec.class));
            }
            reader.endArray();
            LogFactory.info(IjkCodecRegister.class, "从json文件 {} 中读取到{}个配置项", file.getAbsolutePath(), codecs.size());
            return codecs;
        } catch (Exception e) {
            LogFactory.warn(IjkCodecRegister.class, e, "json文件 {} 解析失败", file.getAbsolutePath());
        }
        return null;
    }
}
